package com.zhl.gradledemo.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zhl.gradledemo.model.BrokerMessageLog;
import com.zhl.gradledemo.model.Order;
import com.zhl.gradledemo.producer.OrderSender;
import com.zhl.gradledemo.service.BrokerMessageLogService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 重新发送定时任务
 */
@Component
public class RetryMessageTasker {

    @Resource
    private BrokerMessageLogService brokerMessageLogService;

    @Resource
    private OrderSender orderSender;

    //定时重发
    @Scheduled(initialDelay = 5000, fixedDelay = 10000)
    public void reSend() {
        System.out.println("==定时任务==");
        List<BrokerMessageLog> brokerMessageLogList = brokerMessageLogService.query4StatusAndTimeoutMessage();
        System.out.println("==重发个数==" + brokerMessageLogList.size());
        brokerMessageLogList.forEach(messageLog -> {
            if (messageLog.getTryCount() >= 3) {
                //update fail message
                System.out.println("==重发超过删除,标记为失败==");
                brokerMessageLogService.changeBrokerMessageLogStatus(messageLog.getMessageId(), "2");
            } else {
                // resend
                System.out.println("==再次发送==");
                messageLog.setTryCount(messageLog.getTryCount() + 1);
                messageLog.setUpdateTime(new Date());
                brokerMessageLogService.update(messageLog);

                JSONObject jsonObject = JSONObject.parseObject(messageLog.getMessage());
                Order reSendOrder = JSON.toJavaObject(jsonObject, Order.class);
                try {
                    orderSender.send(reSendOrder);
                } catch (Exception e) {
                    e.printStackTrace();
                    System.err.println("-----------异常处理-----------");
                }
            }
        });
    }

}
